package com.hmall.order.listener;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.OrderDetail;
import com.hmall.common.pojo.Order;
import com.hmall.common.dto.Restore;
import com.hmall.order.service.IOrderService;
import com.hmall.order.web.OrderController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/11/21 17:26
 */
@Component
@Slf4j
public class SubmitOrderListener {

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private OrderController orderController;

    @Autowired
    private ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "submitOrder.queue"),
            exchange = @Exchange(name = "submitOrder.exchange", delayed = "true"),
            key = "submitOrder.key"
    ))
    public void listenSubmitOrder(String orderId){
        log.info("监听到订单的消息了！！！，订单id：{}", orderId);

        // 30分钟之后
        // 判断是否支付
        Order order = iOrderService.getById(orderId);
        if(order.getStatus() != 1){
            return;
        }

        // 未付款
        // 根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderController.queryOrderDetailById(order.getId());

        // 判空
        if(ObjUtil.isEmpty(orderDetails)){
            return;
        }

        // 不为空
        List<Restore> collect = orderDetails.stream().map(orderDetail -> new Restore().builder()
                        .itemId(orderDetail.getItemId())
                        .num(orderDetail.getNum())
                        .build()).collect(Collectors.toList());

        // 重回库存
        itemClient.restore(JSONUtil.toJsonStr(collect));

        // 修改订单状态
        orderController.updateOrder(Long.valueOf(orderId));
    }

}
